﻿using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
	
	public float velocity;
	public float forceJump;
	public float intervalToJump;
	public float intervalForCallAnimation;
	public float intervalAttention;

	private float timeIntervalToJump;
	private float timeIntervalForCallAnimation;
	private float timeIntervalAttention;
	private Transform trans;
	private Rigidbody2D rig2D;
	private Animator animator;
	private bool ready;

	private bool onPlatform;
	
	
	void Start () 
	{
		rig2D = GetComponent<Rigidbody2D>();
		trans = GetComponent<Transform>();
		animator = GetComponent<Animator> ();

		timeIntervalToJump 	= intervalToJump;
		timeIntervalForCallAnimation = intervalForCallAnimation;
		timeIntervalAttention = intervalAttention;
		onPlatform = true;
		ready = false;

		animator.SetInteger ("animation", 0);


		LevelManager.score = 0;
	}
	
	
	void Update () 
	{

		timeIntervalToJump -= Time.deltaTime;
		timeIntervalForCallAnimation -= Time.deltaTime;
		timeIntervalAttention -= Time.deltaTime;

		if(trans.position.y < 1)
		{
			ready = true;
		}

		if(ready)
		{
			if (Input.GetKey(KeyCode.A)) 
			{
				rig2D.AddForce(new Vector2(-velocity, 0));
				animator.SetInteger ("animation", 1);
				timeIntervalAttention = intervalAttention;
				
			}else if (Input.GetKey(KeyCode.D)) 
			{
				rig2D.AddForce(new Vector2(velocity, 0));
				animator.SetInteger ("animation", 2);
				timeIntervalAttention = intervalAttention;
			}
			
			if(Input.GetKeyDown(KeyCode.W))
			{
				if (timeIntervalToJump <= 0) 
				{
					if(onPlatform)
					{
						rig2D.AddForce(new Vector2(0, forceJump));
						timeIntervalToJump = intervalToJump;
						onPlatform = false;
					}
				}
				timeIntervalAttention = intervalAttention;
			}
		}

		// Condicao pra verificar a chamada da animacao
		if(timeIntervalForCallAnimation <= 0)
		{
			animator.Play (0);
			timeIntervalForCallAnimation = intervalForCallAnimation;
		}

		// Condicao pra verificar a chamada da animacao de front, onde o personagem fica olhando pro jogador
		if(timeIntervalAttention <= 0)
		{
			animator.SetInteger("animation", 0);
			timeIntervalAttention = intervalAttention;
		}

		if(trans.position.y <= -6)
		{
			Destroy(gameObject);
			Application.LoadLevel("menu");
		}
	}

	void OnCollisionEnter2D(Collision2D c2D)
	{
		onPlatform = true;

		if(c2D.gameObject.tag == "BonusAddScore")
		{
			Destroy(c2D.gameObject);
			LevelManager.score ++;
		}

		if(c2D.gameObject.tag == "BonusHeart")
		{
			Destroy(c2D.gameObject);
			LevelManager.score ++;
		}

		if(c2D.gameObject.tag == "BonusMultiplier")
		{
			Destroy(c2D.gameObject);
			LevelManager.score ++;
		}
	}
}
